﻿using Dapper.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Mvc;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Models;
using YouWei.Infrastructure.Service;
using YouWei.Op.Common;
using YouWei.Op.Models.Public;
using YouWei.Utility;
using YouWei.Utility.Logging;

namespace YouWei.Op.Controllers
{
    public class PublicController : BaseController
    {
        private CarGroupService carService = new CarGroupService();
        private WxGroupService wxService = new WxGroupService();
        private CarBrandService brandService = new CarBrandService();
        private CarSerialService serialService = new CarSerialService();
        private NoticeService noticeService = new NoticeService();
        private WxGroupUserService wxUserService = new WxGroupUserService();
        private HotMobileService hmService = new HotMobileService();
        private BannerService bpService = new BannerService();
        private VehicleLicenseService vlService = new VehicleLicenseService();
        private CarGroupBrandService ccbService = new CarGroupBrandService();
        private WashShopService wsService = new WashShopService();

        string ImagesUrl = ConfigHelper.GetAppSettingValue("CommentImageServerUrl");

        #region 群组管理
        [AllowAnonymous]
        public ActionResult CarGroupList()
        {
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult GetCarGroupList(ReqCarGroupCondition model)
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<CarGroupDto> page = carService.GetPages(pageIndex, pageSize, model);
            foreach (var item in page.rows)
            {
                item.LogoImageUrl = string.Format("{0}/{1}", ImagesUrl, item.LogoUrl);
                item.QrCodeUrl = string.Format("{0}/{1}", ImagesUrl, item.QrCodeUrl);
            }
            return ReturnResult(page);
        }

        public ActionResult CarGroupEdit()
        {
            CarGroupDto info = new CarGroupDto();
            int id = Utility.EConvert.ToInt(GetParam("id"), 0);
            if (id > 0)
            {
                info = carService.GetInfo(id);
            }
            return View(info);
        }

        /// <summary>
        /// 保存用户
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveCarGroup(ReqCarGroup reqModel)
        {
            var res = new ResultData<string>();
            CarGroup info = null;
            int masterBrandId = 0;
            //CarBrand brandObj = brandService.Single(reqModel.BrandID);
            if (reqModel.BrandID.Count>0)
            {
                masterBrandId = brandService.GetMasterBrandId(reqModel.BrandID[0]);
            }
            if (reqModel.CarGroupID > 0)
            {
                info = carService.Single(reqModel.CarGroupID);
                info.UpdateDate = DateTime.Now;
                info.UpdateUserID = CurrentUser.UserId;
            }
            else
            {
                info = new CarGroup();
                info.CreateDate = DateTime.Now;
                info.CreateUserID = CurrentUser.UserId;
                info.IsActive = 1;
                info.UpdateDate = DefaultTime;
            }

            info.NickName = reqModel.NickName;
            info.QrCodeUrl = reqModel.QrCodeUrl;
            info.Manager = reqModel.Manager;
            info.WxGroupCount = reqModel.WxGroupCount;
            info.CarGroupName = reqModel.CarGroupName;
            // info.BrandID = reqModel.BrandID;
            info.CityID = reqModel.CityID;
            info.HeadUrl = reqModel.HeadUrl;
            info.LogoUrl = reqModel.LogoUrl;
            //    info.ModelID = reqModel.ModelID;
            info.WoManTotal = reqModel.WoManTotal;
            info.ManTotal = reqModel.ManTotal;
            info.Total = info.ManTotal + info.WoManTotal;
            info.Description = reqModel.Description;
            info.MasterBrandID = masterBrandId;

            try
            {
                if (info.CarGroupID <= 0)
                {
                    object id = carService.Insert(info);
                    AddCarGroupBrand(EConvert.ToInt(id), reqModel.BrandID, reqModel.ModelID);
                    foreach (var item in reqModel.ModelID)
                    {
                        AddWxGroupUser(EConvert.ToInt(id), item);
                    }

                }
                else
                {
                    carService.Update(info);
                }
                res.message = "成功";
                res.status = 0;
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                res.message = "添加失败";
                res.status = -1;

            }
            return ReturnResult(res);
        }

        private void AddWxGroupUser(int carGroupId, int modelId)
        {
            List<VehicleUser> list = vlService.GetListByModelId(modelId);
            foreach (var item in list)
            {
                if (!wxUserService.IsExistByUserIdAndCarGroupId(item.UserID, carGroupId))
                {

                    WxGroupUser userObj = new WxGroupUser
                    {
                        IsActive = 1,
                        CreateDate = DateTime.Now,
                        CreateUserID = CurrentUser.UserId,
                        CarGroupID = carGroupId,
                        UserID = item.UserID,
                        Status = 2,
                        OpenID = item.OpenID,
                        UnionID = item.UnionID,
                        UpdateDate = DefaultTime
                    };
                    wxUserService.Insert(userObj);
                }
            }

        }

        private void AddCarGroupBrand(int carGroupId, List<int> brandIds, List<int> modelIds)
        {
            if (brandIds.Count == 0)
            {
                return;
            }
            int i = 0;
            foreach (var item in brandIds)
            {
                CarGroupBrand obj = new CarGroupBrand
                {
                    CarGroupID = carGroupId,
                    CreatedDate = DateTime.Now,
                    MasterBrandID = brandService.GetMasterBrandId(item),
                    BrandID = item,
                    ModelID = modelIds[i]
                };
                ccbService.Insert(obj);
                i++;
            }

        }

        /// <summary>
        /// 删除卡
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelCarGroup(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            CarGroup info = carService.Single(id);
            if (info != null)
            {
                info.IsActive = 0;
                info.UpdateDate = DateTime.Now;
                info.UpdateUserID = CurrentUser.UserId;
                carService.Update(info);
                wxService.BulkDelByCarGroupId(id);
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }

        /// <summary>
        /// 品牌
        /// </summary>
        /// <returns></returns>
        public ContentResult GetBrandList()
        {
            List<CarBrand> list = brandService.QueryAll();
            return ReturnResult(list.Where(m => m.IsActive == 1).OrderBy(m => m.BrandName).ToList());
        }

        /// <summary>
        /// 车型
        /// </summary>
        /// <returns></returns>
        public ContentResult GetSerialList(int brandId)
        {
            List<CarSerial> list = serialService.GetSerialListByBrandId(brandId);
            return ReturnResult(list);
        }

        /// <summary>
        /// 获取单个群组对应的品牌
        /// </summary>
        /// <returns></returns>
        public ContentResult GetGroupBrands(int groupId)
        {
            List<CarGroupBrand> list = ccbService.GetCarGroupBrandList(groupId);
            return ReturnResult(list);
        }
        #endregion

        #region 微信群
        [AllowAnonymous]
        public ActionResult WxGroupList()
        {
            ViewBag.CarGroupId = GetParam("cid");
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult GetWxGroupList(ReqWxGroupCondition model)
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<WxGroup> page = wxService.GetPages(pageIndex, pageSize, model);
            foreach (var item in page.rows)
            {
                item.QrCodeUrl = string.Format("{0}/{1}", ImagesUrl, item.QrCodeUrl);
            }
            return ReturnResult(page);
        }

        public ActionResult WxGroupEdit()
        {
            WxGroup info = new WxGroup();
            int cid = EConvert.ToInt(GetParam("cid"), 0);
            int id = Utility.EConvert.ToInt(GetParam("id"), 0);
            if (id > 0)
            {
                info = wxService.Single(id);
            }
            ViewBag.CarGroupId = cid;
            return View(info);
        }

        /// <summary>
        /// 保存用户
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveWxGroup(ReqWxGroup reqModel)
        {
            var res = new ResultData<string>();
            WxGroup info = null;
            if (reqModel.WxGroupID > 0)
            {
                info = wxService.Single(reqModel.WxGroupID);
                info.UpdateDate = DateTime.Now;
                info.UpdateUserID = CurrentUser.UserId;
            }
            else
            {
                info = new WxGroup();
                info.CreateDate = DateTime.Now;
                info.CreateUserID = CurrentUser.UserId;
                info.IsActive = 1;
                info.UpdateDate = DefaultTime;
            }

            info.Name = reqModel.Name;
            info.CarGroupID = reqModel.CarGroupID;
            info.Total = reqModel.Total;
            info.Desc = reqModel.Desc;
            info.Manager = reqModel.Manager;
            info.NickName = reqModel.NickName;
            info.QrCodeUrl = reqModel.QrCodeUrl;
            info.HeadImgUrl = reqModel.HeadImgUrl;
            try
            {
                if (info.WxGroupID <= 0)
                {
                    wxService.Insert(info);
                }
                else
                {
                    wxService.Update(info);
                }
                res.message = "成功";
                res.status = 0;
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                res.message = "添加失败";
                res.status = -1;

            }
            return ReturnResult(res);
        }

        /// <summary>
        /// 删除卡
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelWxGroup(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            WxGroup info = wxService.Single(id);
            if (info != null)
            {
                info.IsActive = 0;
                info.UpdateDate = DateTime.Now;
                info.UpdateUserID = CurrentUser.UserId;
                wxService.Update(info);
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }

        #endregion

        #region 公告管理
        [AllowAnonymous]
        public ActionResult NoticeList()
        {
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult GetNoticeList(ReqNoticeCondition model)
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<NoticeDto> page = noticeService.GetPages(pageIndex, pageSize, model);
            foreach (var item in page.rows)
            {
                item.NoticeImgUrl = string.Format("{0}/{1}", ImagesUrl, item.NoticeImgUrl);
                item.ShowRangeName = Utility.EnumHelper.GetEnumDesc(typeof(YouWei.Infrastructure.Enums.ShowRangeEnum), item.ShowRange);

            }
            return ReturnResult(page);
        }

        public ActionResult NoticeEdit()
        {
            Notice info = new Notice();
            int id = Utility.EConvert.ToInt(GetParam("id"), 0);
            if (id > 0)
            {
                info = noticeService.Single(id);
            }
            return View(info);
        }

        /// <summary>
        /// 保存用户
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveNotice(ReqNotice reqModel)
        {
            var res = new ResultData<string>();
            Notice info = null;
            if (reqModel.NoticeID > 0)
            {
                info = noticeService.Single(reqModel.NoticeID);
                info.UpdateDate = DateTime.Now;
                info.UpdateUserID = CurrentUser.UserId;
            }
            else
            {
                info = new Notice();
                info.CreateDate = DateTime.Now;
                info.CreateUserID = CurrentUser.UserId;
                info.IsActive = 1;
                info.UpdateDate = DefaultTime;
            }

            info.Comment = reqModel.Comment;
            info.CarGroupID = reqModel.CarGroupID;
            info.GroupLink = reqModel.GroupLink;
            info.NoticeDetail = reqModel.NoticeDetail;
            info.NoticeImgUrl = reqModel.NoticeImgUrl;
            info.ShowRange = reqModel.ShowRange;

            try
            {
                if (info.NoticeID <= 0)
                {
                    noticeService.Insert(info);
                }
                else
                {
                    noticeService.Update(info);
                }
                res.message = "成功";
                res.status = 0;
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                res.message = "添加失败";
                res.status = -1;

            }
            return ReturnResult(res);
        }

        /// <summary>
        /// 删除公告
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelNotice(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            Notice info = noticeService.Single(id);
            if (info != null)
            {
                info.IsActive = 0;
                info.UpdateDate = DateTime.Now;
                info.UpdateUserID = CurrentUser.UserId;
                noticeService.Update(info);
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }

        /// <summary>
        /// 群组
        /// </summary>
        /// <returns></returns>
        public ContentResult GetCarGroupAllList()
        {
            List<CarGroup> list = carService.QueryAll();
            return ReturnResult(list.Where(m => m.IsActive == 1).ToList());
        }
        #endregion

        #region 微信群用户
        [AllowAnonymous]
        public ActionResult WxGroupUserList()
        {
            ViewBag.CarGroupId = GetParam("cid");
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult GetWxGroupUserList(ReqWxGroupUserCondition model)
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<WxGroupUserDto> page = wxUserService.GetPages(pageIndex, pageSize, model);
            return ReturnResult(page);
        }
        #endregion

        #region 热线电话
        [AllowAnonymous]
        public ActionResult HotMobileList()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        public ContentResult GetHotMobileList()
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<HotMobile> page = hmService.GetPages(pageIndex, pageSize);
            foreach (var item in page.rows)
            {
                item.MobileLogoUrl = string.Format("{0}/{1}", ImagesUrl, item.MobileLogo);
            }
            return ReturnResult(page);
        }

        public ActionResult HotMobileEdit()
        {
            HotMobile info = new HotMobile();
            int id = Utility.EConvert.ToInt(GetParam("id"), 0);
            if (id > 0)
            {
                info = hmService.Single(id);
            }
            return View(info);
        }

        /// <summary>
        /// 保存用户
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveHotMobile(ReqHotMobile reqModel)
        {
            var res = new ResultData<string>();
            HotMobile info = null;
            if (reqModel.MobileID > 0)
            {
                info = hmService.Single(reqModel.MobileID);
                info.UpdateDate = DateTime.Now;
                info.UpdateUserID = CurrentUser.UserId;
            }
            else
            {
                info = new HotMobile();
                info.CreateDate = DateTime.Now;
                info.CreateUserID = CurrentUser.UserId;
                info.IsActive = 1;
                info.UpdateDate = DefaultTime;
            }

            info.Mobile = reqModel.Mobile;
            info.MobileLogo = reqModel.MobileLogo;
            info.MobileSort = reqModel.MobileSort;
            info.MobileGroup = reqModel.MobileGroup;
            info.MobileDesc = reqModel.MobileDesc;


            try
            {
                if (info.MobileID <= 0)
                {
                    hmService.Insert(info);
                }
                else
                {
                    hmService.Update(info);
                }
                res.message = "成功";
                res.status = 0;
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                res.message = "添加失败";
                res.status = -1;

            }
            return ReturnResult(res);
        }

        /// <summary>
        /// 删除公告
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelHotMobile(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            HotMobile info = hmService.Single(id);
            if (info != null)
            {
                info.IsActive = 0;
                info.UpdateDate = DateTime.Now;
                info.UpdateUserID = CurrentUser.UserId;
                hmService.Update(info);
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }
        #endregion

        #region 轮循广告
        [AllowAnonymous]
        public ActionResult BannerList()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        public ContentResult GetBannerList()
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<Banner> page = bpService.GetPages(pageIndex, pageSize);
            foreach (var item in page.rows)
            {
                item.DetailImageUrl = string.Format("{0}/{1}", ImagesUrl, item.ImageUrl);
                item.CategoryName = Utility.EnumHelper.GetEnumDesc(typeof(Infrastructure.Enums.BannerCategoryEnum), item.Category);
            }
            return ReturnResult(page);
        }

        public ActionResult BannerEdit()
        {
            Banner info = new Banner();
            int id = Utility.EConvert.ToInt(GetParam("id"), 0);
            if (id > 0)
            {
                info = bpService.Single(id);
            }
            return View(info);
        }

        /// <summary>
        /// 保存用户
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveBanner(ReqBanner reqModel)
        {
            var res = new ResultData<string>();
            Banner info = null;
            if (reqModel.BannerID > 0)
            {
                info = bpService.Single(reqModel.BannerID);
                info.UpdateTime = DateTime.Now;

            }
            else
            {
                info = new Banner();
                info.CreateTime = DateTime.Now;
                info.IsActive = 1;
                info.UpdateTime = DefaultTime;
            }

            info.Category = reqModel.Category;
            info.ImageUrl = reqModel.ImageUrl;
            info.LinkUrl = reqModel.LinkUrl;
            info.Description = reqModel.Description;

            try
            {
                if (info.BannerID <= 0)
                {
                    bpService.Insert(info);
                }
                else
                {
                    bpService.Update(info);
                }
                res.message = "成功";
                res.status = 0;
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                res.message = "添加失败";
                res.status = -1;

            }
            return ReturnResult(res);
        }

        /// <summary>
        /// 删除公告
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelBanner(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            Banner info = bpService.Single(id);
            if (info != null)
            {
                info.IsActive = 0;
                info.UpdateTime = DateTime.Now;
                bpService.Update(info);
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }
        #endregion

        #region 洗车管理
        public ActionResult WashShopIndex()
        {
            return View();
        }
        public PartialViewResult WashShopParList(WashShopSearchModel model)
        {
            try
            {
                var pageIndex = Convert.ToInt32(GetParam("page"));
                var pageSize = GetPageSize();
                var page = wsService.Pages(pageIndex, pageSize, model);
                ViewBag.Total = page.total;
                ViewBag.PageIndex = pageIndex;
                ViewBag.PageSize = pageSize;
                return PartialView(page.rows);
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                return PartialView();
            }
        }
        public ActionResult WashShopEdit()
        {
            string CommentImageServerUrl = ConfigHelper.GetAppSettingValue("CommentImageServerUrl");
            var id = Convert.ToInt32(GetParam("id"));
            var model = new WashShop();
            if (id > 0)
                model = wsService.Single(id);
            else
                model = new WashShop();
            //图片拼上服务器地址
            if (!string.IsNullOrWhiteSpace(model.ImageUrl))

                ViewBag.ImageUrl = CommentImageServerUrl + "/" + model.ImageUrl;
            else
                ViewBag.ImageUrl = "";

            ViewBag.WashShopID = id;
            return View(model);
        }
        [HttpPost]
        public ActionResult WashShopDelete(WashShop model)
        {
            ResultData<int> rt = ResultData<int>.Success();
            var id = GetParam<int>("id");
            if (id > 0)
            {
                var entity = wsService.Single(id);
                entity.IsActive = 0;
                entity.UpdateDate = DateTime.Now;
                if (wsService.Update(entity))
                {
                    rt.data = id;
                }
                else
                {
                    rt.status = -1;
                    rt.message = "更新失败";
                }
            }
            else
            {
                rt.status = -1;
                rt.message = "不存在此项";
            }
            return ReturnResult(rt);
        }
        [HttpPost]
        public ActionResult WashShopSave(WashShop model)
        {
            ResultData<int> rt = ResultData<int>.Success();
            var id = GetParam<int>("id");
            if (string.IsNullOrWhiteSpace(model.WashName))
            {
                rt.message = "名称不能为空";
                rt.status = -1;
                return ReturnResult(rt);
            }

            if (string.IsNullOrWhiteSpace(model.Address))
            {
                rt.message = "地址不能为空";
                rt.status = -1;
                return ReturnResult(rt);
            }
            if (string.IsNullOrWhiteSpace(model.WorkTime))
            {
                rt.message = "工作时间不能为空";
                rt.status = -1;
                return ReturnResult(rt);
            }
            if (id > 0)
            {
                //edit
                var entity = wsService.Single(id);
                entity.WashName = model.WashName;
                entity.WorkTime = model.WorkTime;
                entity.ImageUrl = model.ImageUrl;
                entity.Latitude = model.Latitude;
                entity.Longitude = model.Longitude;
                entity.ProvinceID = model.ProvinceID;
                entity.UpdateDate = DateTime.Now;
                if (wsService.Update(entity))
                {
                    rt.data = id;
                }
                else
                {
                    rt.status = -1;
                    rt.message = "更新失败";
                }
            }
            else
            {
                //add
                model.IsActive = 1;
                model.CreateDate = DateTime.Now;
                rt.data = Convert.ToInt32(wsService.Insert(model));
            }
            return ReturnResult(rt);
        }
        public ActionResult Map()
        {
            return View();
        }
        #endregion
    }
}
